package com.think.excel;

import org.springframework.boot.context.config.ConfigDataLocation;
import org.springframework.boot.context.config.ConfigDataLocationNotFoundException;
import org.springframework.boot.context.config.ConfigDataLocationResolver;
import org.springframework.boot.context.config.ConfigDataLocationResolverContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class ExcelConfigDataLocationResolver implements ConfigDataLocationResolver<ExcelConfigDataResource> {
    private static final String PREFIX = "excel:";

    @Override
    public boolean isResolvable(ConfigDataLocationResolverContext context, ConfigDataLocation location) {
        return location.getValue().startsWith(PREFIX);
    }

    @Override
    public List<ExcelConfigDataResource> resolve(ConfigDataLocationResolverContext context, ConfigDataLocation location) throws ConfigDataLocationNotFoundException, ConfigDataResourceNotFoundException {
        // 1. 提取路径并去除前缀
        String path = location.getValue().substring(PREFIX.length());

        try {
            // 从 Binder 获取 ResourceLoader
            ResourceLoader resourceLoader = context.getBinder()
                    .bind("spring.resources.ExcelResourceLoader", ResourceLoader.class)
                    .orElseGet(DefaultResourceLoader::new);

            // 转换为支持通配符的解析器
            ResourcePatternResolver patternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader);
            Resource[] resources = patternResolver.getResources(path);

            return Arrays.stream(resources)
                    .map(ExcelConfigDataResource::new)
                    .toList();
        } catch (IOException e) {
            throw new ConfigDataResourceNotFoundException(null, e);
        }
    }
}
